package com.motorhome.h5.controller;

import com.motorhome.base.util.Result;
import com.motorhome.h5.domain.User;
import com.motorhome.h5.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: John
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @RequestMapping(value = "/login")
    public String login(HttpServletRequest request, Model model) {
        model.addAttribute("openId", request.getParameter("openId"));
        model.addAttribute("source", request.getParameter("source"));
        return "login/login";
    }

    @RequestMapping(value = "/doLogin", method = RequestMethod.POST)
    public @ResponseBody Result doLogin(HttpServletRequest request, HttpServletResponse response) {
        String phone = request.getParameter("username");
        String code = request.getParameter("code");
        String openId = request.getParameter("openId");
        return loginService.doLogin(request, response, phone, code, openId);
    }

    @RequestMapping(value = "/reg")
    public String reg() {
        return "reg/reg";
    }

    @RequestMapping(value = "/reg2")
    public String reg2() {
        return "reg/reg2";
    }

    @RequestMapping(value = "/doReg", method = RequestMethod.POST)
    public @ResponseBody Result doReg(HttpServletRequest request, HttpServletResponse response) {
        User loginUser = (User)request.getAttribute("loginUser");
        String password = (String)request.getAttribute("passwd");
        String realName = (String)request.getAttribute("realname");
        return loginService.doReg(loginUser, password, realName);
    }

    @RequestMapping(value = "/sendCode", method = RequestMethod.POST)
    public @ResponseBody Result sendCode(HttpServletRequest request, HttpServletResponse response) {
        String phone = request.getParameter("phone");
        return loginService.sendCode(phone);
    }

}
